package com.dd.shop4j.common.utils.security;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dd.shop4j.admin.mapper.AdminLogsMapper;
import com.dd.shop4j.admin.mapper.AdminUserMapper;
import com.dd.shop4j.admin.model.AdminLogs;
import com.dd.shop4j.admin.model.AdminUser;

/**
 * 账户管理Service，该类主要负责权限控制和账户管理
 * @author tangshu
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AccountService {

	@Resource
	private AdminUserMapper adminUserMapper;
	
	@Resource
	private AdminLogsMapper adminLogsMapper;
	
	/**
	 * 根据用户名 获取用户信息
	 * @param username
	 * @return
	 */
	public AdminUser getAdminUserByUsername(String username) {
		AdminUser entity = new AdminUser();
		entity.setUsername(username);
		List<AdminUser> adminUsers = adminUserMapper.queryBySelective(entity);
		if (CollectionUtils.isNotEmpty(adminUsers)) {
			return adminUsers.get(0);
		}
		return null;
	}
	
	/**
	 * 记录并更新用户登录信息
	 * @param userId	登录用户id
	 * @param host		登录的ip
	 */
	public void loginAdminUser(Integer userId, String host) {
		//获取当前时间
		Date curDate = new Date();
		
		//根据用户id，更新用户的最后登录时间 和 最后登录ip
		AdminUser entity = new AdminUser();
		entity.setUserId(userId);
		entity.setLastLogin(curDate);
		entity.setLastIp(host);
		adminUserMapper.updateSelectiveByPrimaryKey(entity);
		
		//将用户登录记录到管理员日志中
		AdminLogs adminLog = new AdminLogs();
		adminLog.setAddTime(curDate);
		adminLog.setUserId(userId);
		adminLog.setContent("管理员用户登录后台");
		adminLog.setOperatIp(host);
		adminLogsMapper.insertSelective(adminLog);
	}
	
	/**
	 * 根据用户id得到该用的所有角色code
	 * @param userId	用户id
	 * @return	角色code
	 */
	public List<String> getRolesCodeByUserId(Integer userId) {
		return adminUserMapper.getRolesCodeByUserId(userId);
	}
	
	/**
	 * 根据用户id得到该用户的所有资源code
	 * @param userId	用户id
	 * @return	资源code
	 */
	public List<String> getResourcesCodeByUserId(Integer userId) {
		return adminUserMapper.getResourcesCodeByUserId(userId);
	}

	/**
	 * 加载系统的权限过滤Shiro表达式
	 * @return  Shiro表达式字符串
	 */
	public String loadFilterChainDefinitions() {
		String newLine = "\r\n";
		StringBuffer filterChainDefinitions = new StringBuffer();
		filterChainDefinitions.append(newLine);
		return filterChainDefinitions.toString();
	}
}
